package projectiles
{
	import enemies.Enemy;
	
	import flash.display.MovieClip;
	import flash.geom.Point;
	
	import units.Unit;
	
	public class Enemy_Projectile extends MovieClip
	{
		public var game_handler:GameHandler;
		public var source:Enemy;
		public var died = false;
		public var speed = 3;
		public var attack_damage = 1;
		public var frame_life = 0;
		public function Enemy_Projectile(s:Enemy,gH:GameHandler)
		{
			super();
			game_handler=gH;
			source = s;
			this.x=s.x;
			this.y=s.y;
			game_handler.projectiles.push(this);
			game_handler.addChild(this);
		}
		
		public function set_attack_damage(amt){
			attack_damage = amt;
		}
		public function set_speed(spd){
			speed = spd;
		}
		public function run(){
			frame_life ++;
			move();
		}
		public function move(){
			var dist = get_distance_to_castle();
			if (dist < 125)
				end_move();
			var target_point = get_direction_of_castle();
			this.x += speed*target_point.x;
			this.y += speed*target_point.y;
			
		}
		public function end_move(){
			if(died)
				return;
			game_handler.mana_amount -= attack_damage;
			die();
		}
		public function get_direction_of_castle(){
			var y_diff = game_handler.castle_center.y - this.y;
			var x_diff = game_handler.castle_center.x - this.x;
			var y_diff_sq = y_diff*y_diff;
			var x_diff_sq = x_diff*x_diff;
			
			if(x_diff_sq + y_diff_sq == 0)
				return new Point(0,0);
			
			return new Point( x_diff / Math.abs(x_diff) * (x_diff_sq/(x_diff_sq+y_diff_sq)),y_diff / Math.abs(y_diff) * (y_diff_sq/(x_diff_sq+y_diff_sq)));
		}
		public function get_distance_to_castle(){
			var y_diff = game_handler.castle_center.y - this.y;
			var x_diff = game_handler.castle_center.x - this.x;
			var y_diff_sq = y_diff*y_diff;
			var x_diff_sq = x_diff*x_diff;
			return Math.sqrt(y_diff_sq + x_diff_sq);
		}
		public function die(){
			if(died)
				return;
			died = true;
			var my_spot=-1;
			for(var i:int = 0; i < game_handler.projectiles.length; i++)
				if(game_handler.projectiles[i] == this)
					my_spot = i;
			if(my_spot != -1)
				game_handler.projectiles.splice(my_spot,1);
			game_handler.removeChild(this);
		}
	}
}